package com.bayss.core.service.user;


import com.bayss.core.DokoServerException;
import com.bayss.core.DokoServerExceptionFactor;
import com.bayss.core.entity.user.UserInfo;
import com.bayss.core.entity.user.UserInfoExample;
import com.bayss.core.entity.user.mapper.UserInfoMapper;
import com.bayss.core.util.RedisUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class UserService {

    private static Logger logger = LogManager.getLogger();

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    RedisUtil redisUtil;


    public void UserService(UserInfoMapper userInfoMapper) {
        this.userInfoMapper = userInfoMapper;
    }

    public UserInfo login(String openid, String nickName, String avatarUrl, String gender) {
        UserInfo userInfo = getUser(openid);
        if (userInfo != null) {
            return userInfo;
        }

        userInfo = UserInfo.builder()
                .openId(openid)
                .nickname(nickName)
                .headPortraitUrl(avatarUrl)
                .gender(Integer.parseInt(gender))
                .status(1)
                .type(1)
                .balance(0)
                .build();
        boolean res = userInfoMapper.insertSelective(userInfo) > 0;
        if (!res) {
            throw new DokoServerException(DokoServerExceptionFactor.DEFAULT, "add user is fail");
        }
        return userInfo;
    }

    public boolean updateBalance(long uid, Integer balance) {
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(uid);
        Integer ba = userInfo.getBalance();
        if (ba == null || ba < -balance) {
            throw new DokoServerException(DokoServerExceptionFactor.BALANCE_FAIL);
        }
        userInfo.setBalance(ba + balance);
        return userInfoMapper.updateByPrimaryKey(userInfo) > 0;
    }

    public boolean updateTel(String tel, Long uid, String code) {
        Object res = redisUtil.get(uid + "-" + code);
        if (res != null && (int) res == 1) {
            UserInfo userInfo = userInfoMapper.selectByPrimaryKey(uid);
            userInfo.setCellphone(tel);
            return userInfoMapper.updateByPrimaryKeySelective(userInfo) > 0;
        }
        return false;
    }

    public boolean updateToPay(Long uid, Integer toPay) {
        return userInfoMapper.updateByPrimaryKeySelective(UserInfo.builder().id(uid).canToPay(toPay.byteValue()).build()) > 0;
    }


    public void updateUserInfo(UserInfo userInfo) {
        userInfoMapper.updateByPrimaryKeySelective(userInfo);
    }

    public UserInfo getUser(Long uid) {
        return userInfoMapper.selectByPrimaryKey(uid);
    }

    public PageInfo<UserInfo> getUsers(Integer page, Integer pageSize, long start, long end, long birStart, long birEnd, int gender, String cellphone, Integer userType) {
        UserInfoExample userInfoExample = new UserInfoExample();
        userInfoExample.setOrderByClause("id asc");
        UserInfoExample.Criteria criteria = userInfoExample.createCriteria();
        if (start > 0) {
            criteria.andCreateTimeGreaterThanOrEqualTo(new Date(start));
        }
        if (end > 0) {
            criteria.andCreateTimeLessThanOrEqualTo(new Date(end));
        }
        if (birStart > 0) {
            criteria.andBirthdayGreaterThanOrEqualTo(new Date(birStart));
        }
        if (birEnd > 0) {
            criteria.andBirthdayLessThanOrEqualTo(new Date(birEnd));
        }
        if (gender != -1) {
            criteria.andGenderEqualTo(gender);
        }
        if (!StringUtils.isEmpty(cellphone)) {
            criteria.andCellphoneEqualTo(cellphone);
        }
        if (userType == 1) {
            criteria.andBalanceEqualTo(0);//普通用户
        }
        if (userType == 2) {
            criteria.andBalanceGreaterThan(0);//充值用户
        }
        PageInfo<UserInfo> pageInfo = PageHelper.startPage(page, pageSize).doSelectPageInfo(() -> userInfoMapper.selectByExample(userInfoExample));
        return pageInfo;
    }

    public UserInfo getUser(String openid) {
        UserInfoExample userInfoExample = new UserInfoExample();
        UserInfoExample.Criteria criteria = userInfoExample.createCriteria();
        criteria.andOpenIdEqualTo(openid);
        List<UserInfo> userInfos = userInfoMapper.selectByExample(userInfoExample);
        if (userInfos.size() == 0) {
            return null;
        }
        return userInfos.get(0);
    }

    public List<UserInfo> getUserByName(String name) {
        UserInfoExample userInfoExample = new UserInfoExample();
        UserInfoExample.Criteria criteria = userInfoExample.createCriteria();
        criteria.andNicknameLike(name);
        return userInfoMapper.selectByExample(userInfoExample);
    }

    /**
     * 在小程序用户中查找系统管理员特殊账号（用户系统管理员的评论）
     *
     * @return
     */
    public UserInfo getSystemUser() {
        UserInfoExample userInfoExample = new UserInfoExample();
        UserInfoExample.Criteria criteria = userInfoExample.createCriteria();
        criteria.andTypeEqualTo(0);
        return userInfoMapper.selectByExample(userInfoExample).get(0);
    }
}
